<?php


namespace app\index\controller;

use think\Controller;
use app\common\model\User as UserModel;
use app\common\model\Userinfo as UserInfoModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Sell as SellModel;
use app\common\model\Produce as ProduceModel;
use think\helper\Str;
use think\Loader;
use think\Request;
use think\Db;
use think\Session;

class Index extends Controller
{

    //登录界面
    public function index(){
        return $this->fetch();
    }

    //    实现登陆功能
    public function do_login()
    {
        //获取表单提交的信息
        $data=$this->request->post();
//        dump($data);

        $user = new UserModel();
        $userInfo = new UserInfoModel();
        $one =$userInfo->where(['name'=>$data['name'],'class'=>$data['class']])->find();
        $user_id = $one['uID'];
        if($user_id){
            $result=$user->where(['uID'=>$user_id,'pwd'=>$data['pwd'],'class'=>$data['class']])->find();
            if($result){
                Session::set('name', $data['name']);
                Session::set('uID', $result['uID']);
                Session::set('rID', $one['rID']);
                Session::set('class', $data['class']);
                if($one['class']=='G'){ //政府
                    return $this->redirect('index/home');
                }else if($one['class']=='Q'){ //企业
                    $cVerify = Db::query("select cVerify from company where cID=:cID",['cID'=>$result['uID']])[0]['cVerify'];
                    Session::set('cVerify', $cVerify);
                    // 判断企业状态，去往不同主页
                    if ($cVerify == 1)
                        return $this->redirect('company/home');
                    else
                        return $this->redirect('company/otherHome');
                }

            }else{
                return $this->error('密码错误');
            }
        }else{
            return $this->error('用户名或用户类型错误');
        }
    }

    //渲染register
    public function register(){
        $regionList = Db::table('region')->select();
        $this->assign("regionList",$regionList);
        return $this->fetch();
    }

    //查看是否已有用户名
    public function getName(){
        $post_name = $this->request->post()['name'];
        $company = new CompanyModel();
        $name = $company->where('name','eq',$post_name)->find();
//        dump($name);
        if($name){
            $result['valid'] = "false";
        }else{
            $result['valid'] = "true";
        }
        return $result;
    }

    //实现注册
    public function do_register(){
        $form = $this->request->post();
        $userinfo = new UserInfoModel();
        $user = new UserModel();
        $company = new CompanyModel();
//        dump($form);
        $form['class'] = "Q";
        //先存userinfo表
        $userinfo->allowField(true)->save($form);
        //设置uID和cID 相同
        $uID = $userinfo->where('name','=',$form['name'])->find()['uID'];
        $form['uID'] = $uID;
        $form['cID'] = $uID;

        //存入userinfo表和company表
        $user->allowField(true)->save($form);
        $company->allowField(true)->save($form);

        $result['success'] = "true";
        return $result;
    }

    //退出登录
    public function logout()
    {
        session(null);
        return $this->success('已成功退出！','index/index');
    }

    //渲染修改信息页面
    public function updMes(){
        $uID = Session::get('uID');
        $one = Db::query("select pwd,r.name region,a.* from userinfo a join `user` using(`uID`) join region r using(`rID`) where uID=$uID")[0];
        //赋值
        $this->assign([
            'name'=>$one['name'],
            'region'=>$one['region'],
            'email'=>$one['email'],
            'mobile'=>$one['mobile'],
            'regTime'=>$one['regTime'],
            'pwd'=>$one['pwd']
        ]);
        return $this->fetch();
    }

    //修改信息
    public function doUpdMes(){
        $user = new UserModel();
        $userinfo = new UserInfoModel();
        $data = $this->request->post();
        $data['uID'] = Session::get('uID');
//        dump($data);
        $userinfo->allowField(true)->isUpdate(true)->save($data);
        $result['success'] = "true";
        return $result;
    }

    //渲染首页，填充数据
    public function home(){
        $company = new CompanyModel();
        $goods = new GoodsModel();
        $sell = new SellModel();
        $produce = new ProduceModel();


        /** 四个便签的数据 **/
        $rID = Session::get('rID');
        $company_num = $company->where(['rID'=>$rID])->count();
        $company_ids = $company->where(['rID'=>$rID])->column('cID');
        $goods_num = $goods->where('cID','IN',$company_ids)->count();
        $gIds = $goods->where('cID','IN',$company_ids)->column('gID');
        $pIDs = $produce->where('gID','IN',$gIds)->column('pID');
        $sell_result = $sell->where('pID','IN',$pIDs)->select();
        $sell_num = $sell->where('pID','IN',$pIDs)->count();
        /* 统计该地区总共交易总额 */
        $total_price = 0;
        foreach ($sell_result as $item){
            $uNum = $item['uNum'];
            $price = $produce->where('pID','=',$item['pID'])->column('gPrice')[0];
            $total_price = $total_price + (int)$uNum * (float)$price;
        }
        /* 赋值 */
        $this->assign([
            'company_num' => $company_num,
            'goods_num' => $goods_num,
            'sell_num' => $sell_num,
            'total_price' => $total_price
        ]);

        /** 图表数据 按月统计 **/
        $rID = Session::get('rID');
        $year = date('Y'); //获取当前年份
        /* 分月企业注册数 */
        //通过sql语句获取每月总数，结果为数组
        $temp_total = Db::query("SELECT date_format(regTime,'%m') mon,count(*) total from userinfo where date_format(regTime,'%Y')=$year and class='Q' GROUP BY mon order by mon");
        $len = count($temp_total); //获得数组长度
        $company_total = [];//用来存放各月总数
//        dump($temp_total);
        //为$company_total赋值
        for ($i=0,$j=0;$i<12;$i++) {
            if ($j < $len) {
                if (($i+1) == (int)$temp_total[$j]['mon']) { //arr[0]==1月总数，以此类推
                    $company_total[$i] = (int)$temp_total[$j]["total"];
                    $j = $j + 1;
                } else {
                    $company_total[$i] = 0;
                }
            }else{
                $company_total[$i] = 0;
            }
        }
        /* 分月总销售额 */
        $temp_total = Db::query("select date_format(uRDate,'%m') mon,sum(uPrice) price from sell where date_format(uRDate,'%Y')=$year and pID in (select pID from produce where gID in (select gID from goods where cID in (select cID from company where rID=$rID))) group by mon order by mon");
        $len = count($temp_total); //获得数组长度
        $price_total = [];//用来存放各月总数
//        dump($temp_total);
        //为$price_total赋值
        for ($i=0,$j=0;$i<12;$i++) {
            if ($j < $len) {
                if (($i+1) == (int)$temp_total[$j]['mon']) { //arr[0]==1月总数，以此类推
                    $price_total[$i] = (float)$temp_total[$j]["price"];
                    $j = $j + 1;
                } else {
                    $price_total[$i] = 0.0;
                }
            }else{
                $price_total[$i] = 0.0;
            }
        }
        /* 分月总订单数 */
        $temp_total = Db::query("select date_format(uRDate,'%m') mon,count(*) total from sell where date_format(uRDate,'%Y')=$year and pID in (select pID from produce where gID in (select gID from goods where cID in (select cID from company where rID=$rID))) group by mon order by mon");
        $len = count($temp_total); //获得数组长度
        $sell_total = [];//用来存放各月总数
//        dump($temp_total);
        //为$price_total赋值
        for ($i=0,$j=0;$i<12;$i++) {
            if ($j < $len) {
                if (($i+1) == (int)$temp_total[$j]['mon']) { //arr[0]==1月总数，以此类推
                    $sell_total[$i] = (int)$temp_total[$j]["total"];
                    $j = $j + 1;
                } else {
                    $sell_total[$i] = 0;
                }
            }else{
                $sell_total[$i] = 0;
            }
        }

        /* 渲染js中的数组变量 */
        $this->assign('company_total',$company_total);
        $this->assign('price_total',$price_total);
        $this->assign('sell_total',$sell_total);

        // 渲染模板
        return $this->fetch();
    }


    /** 企业管理 **/
    //渲染企业管理界面
    public function company(){
        $company = new CompanyModel();
        $pendingList = $company->where([
            'rID' => Session::get('rID'),
            'cVerify' => 2
        ])->select();
        $this->assign('pendingList',$pendingList);
        $allList = $company->where('rID','eq',Session::get('rID'))->select();
        $this->assign('allList',$allList);
        return $this->fetch();
    }
    /** 企业管理结束 **/

    
    /** 生产管理 **/

    //渲染生产管理
    public function produce(){
//        $company = new CompanyModel();
//        $goods = new GoodsModel();
//        $produce = new ProduceModel();
//
//        $rID = Session::get('rID');
//
//        $pendingList = Db::query("select p.*,g.gName,g.gImg from produce p join goods g using(`gID`) where gID in (select gID from goods where cID in (select cID from company where rID=:rID)) and cVerify=2",['rID'=>$rID]);
//        $allList = Db::query("select p.*,g.gName,g.gImg from produce p join goods g using(`gID`) where gID in (select gID from goods where cID in (select cID from company where rID=:rID))",['rID'=>$rID]);
//        $this->assign('pendingList',$pendingList);
//        $this->assign('allList',$allList);
        return $this->fetch();
    }
    public function getPendingList(){
        $company = new CompanyModel();
        $goods = new GoodsModel();
        $produce = new ProduceModel();

        $rID = Session::get('rID');
        $pendingList = Db::query("select p.*,g.gName,g.gImg from produce p join goods g using(`gID`) where gID in (select gID from goods where cID in (select cID from company where rID=:rID)) and cVerify=2",['rID'=>$rID]);
        return json($pendingList);
    }
    public function getAllList(){
        $company = new CompanyModel();
        $goods = new GoodsModel();
        $produce = new ProduceModel();

        $rID = Session::get('rID');
        $allList = Db::query("select p.*,g.gName,g.gImg from produce p join goods g using(`gID`) where gID in (select gID from goods where cID in (select cID from company where rID=:rID))",['rID'=>$rID]);
        return json($allList);
    }

    /** 生产管理结束 **/

    /** 共用 **/
    //通过
    public function doApprove(){
        $data = $this->request->get();
        // 判断是企业管理还是生产管理
        if(isset($data['cID'])){ //企业管理
            $cID = $data['cID'];
            $company = new CompanyModel();
            $company->save(['cVerify'=>1],['cID'=>$cID]);
            return $this->redirect('index/company');
        }elseif (isset($data['pID'])){ //生产管理
            $pID = $data['pID'];
            $produce = new ProduceModel();
            $produce->save(['cVerify'=>1],['pID'=>$pID]);
            return $this->redirect('index/produce');
        }

    }

    //不通过
    public function doDeny(){
        $data = $this->request->get();
        // 判断是企业管理还是生产管理
        if(isset($data['cID'])){ //企业管理
            $cID = $data['cID'];
            $company = new CompanyModel();
            $company->save(['cVerify'=>0],['cID'=>$cID]);
            return $this->redirect('index/company');
        }elseif (isset($data['pID'])){ //生产管理
            $pID = $data['pID'];
            $produce = new ProduceModel();
            $produce->save(['cVerify'=>0],['pID'=>$pID]);
            return $this->redirect('index/produce');
        }
    }

    /* 修改密码 */
    public function updPwd(){
        return $this->fetch();
    }
    public function checkPwd(){
        $post_pwd = $this->request->post()['pwd'];
        $uID = Session::get('uID');
        $pwd = Db::query("select pwd from user where uID=$uID")[0]['pwd'];
        if($post_pwd == $pwd){
            $result['valid'] = "true";
        }else{
            $result['valid'] = "false";
        }
        return $result;
    }

    public function doUpdPwd(){
        $data['pwd'] = $this->request->post()['new_pwd'];
        $data['uID'] = Session::get('uID');
        $user = new UserModel();
        $user->allowField(true)->isUpdate(true)->save($data);
        $result['success'] = "true";
        return $result;
    }

    /** 共用结束 **/

    public function test(){
        return $this->fetch();
    }
    public function testImg(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');

        if($file){
            // 指定规则  其中md5和sha1规则会自动以散列值的前两个字符作为子目录，后面的散列值作为文件名。
            // 保存路径 public/uploads/goodsImg
            $info = $file->rule('md5')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'goodsImg');
            if($info){
                //输出 => 子目录/文件名
                echo $info->getSaveName();
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }
    public function testQrCode(){
        Loader::import('qrcode.phpqrcode',EXTEND_PATH, '.php');
        $data = $this->request->post();//二维码内容
        $value = "产品销售码为：".date('dHis').time().rand(10000,9999999);
//        $value = "22222222222";//二维码内容
//        dump($value);
        $matrixPointSize = 10;
        $errorCorrectionLevel = 'H';  //容错级别
        $margin=2;
        //生成二维码图片
        //设置二维码文件名
        $head_path = ROOT_PATH. 'public' . DS . 'uploads';
        $filename = 'gSellCodeImg'. DS .time().rand(10000,9999999).'.png'; //存入数据库的文件名
        $img_path = $head_path . DS . $filename;
//        dump($filename);
        //生成二维码
        \QRcode::png($value, $img_path ,$errorCorrectionLevel, $matrixPointSize, $margin);

        //以下是二维码中带上logo,根据需要使用
        $logo = ROOT_PATH. DS .'public/static/img/logo.jpeg';//准备好的logo图片
        $QR = $img_path;//已经生成的原始二维码图
        if ($logo !== FALSE) {
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
        }
        imagepng ($QR, $img_path );//重新生成二维码图片
        $result['success'] = "true";
        dump($filename);
//        return $result;
    }

}